package com.kstudio.videocapture.listimage;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;

import com.kstudio.videocapture.util.KUtil;
import com.kstudio.videocapture.util.bitmapload.BitmapDoubleCache;

public class KImageListLoadBitmap extends BitmapDoubleCache<KImageListLoadBitmapParam> {
    private static final int MSG_UI_UPDATE = 0x0001;

    private int mBmWidth  = 100;
    private int mBmHeight = 100;

    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_UI_UPDATE:
                    Param p = (Param) msg.obj;

                    KImageListLoadBitmapParam param = p.param;
                    KImageListViewWrapper wrapper = param.getViewWrapper();

                    if(wrapper.getPosition() == param.getPosition() && !wrapper.isLoaded()) {
                        wrapper.setLoadBitmap(p.bm);
                    }
                    break;
            }
        }
    };

    private class Param {
        KImageListLoadBitmapParam param;
        Bitmap bm;

        Param(KImageListLoadBitmapParam param, Bitmap bm) {
            this.param = param;
            this.bm = bm;
        }
    }

    public KImageListLoadBitmap(Context context, String uniqueName, int MemoryCacheSize, int diskCacheSize) {
        super(context, uniqueName, MemoryCacheSize, diskCacheSize);
    }

    public void setBitmapSize(int bmWidth, int bmHeight) {
        mBmWidth = bmWidth;
        mBmHeight = bmHeight;
    }

    public KImageListLoadBitmapParam createParam(KImageListViewWrapper viewWrapper, int position) {
        return new KImageListLoadBitmapParam(viewWrapper, position);
    }

    @Override
    protected void onLoadBitmapUpdateFromCache(KImageListLoadBitmapParam obj, Bitmap bm) {
        Message msg = mHandler.obtainMessage();
        msg.what = MSG_UI_UPDATE;
        msg.obj = new Param(obj, bm);
        mHandler.sendMessage(msg);
    }

    @Override
    protected Bitmap loadBitmap(String filename) {
        return KUtil.fastLoadBitmapResizedOnRatio(filename, mBmWidth, mBmHeight);
    }
}
